<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 生产排程
 * @icon fa fa-calendar-check-o
 */
class Schedule extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Schedule;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->where($where)->order($sort, $order)->paginate($limit);
            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 验证必填字段
                if (empty($params['schedule_name'])) {
                    $this->error('排程名称不能为空');
                }
                if (empty($params['start_date'])) {
                    $params['start_date'] = date('Y-m-d');
                }
                if (empty($params['end_date'])) {
                    $params['end_date'] = date('Y-m-d', strtotime('+7 days'));
                }
                
                // 验证日期格式
                if (!strtotime($params['start_date'])) {
                    $this->error('开始日期格式不正确');
                }
                if (!strtotime($params['end_date'])) {
                    $this->error('结束日期格式不正确');
                }
                
                // 验证日期逻辑
                if (strtotime($params['start_date']) > strtotime($params['end_date'])) {
                    $this->error('开始日期不能晚于结束日期');
                }
                
                // 自动生成排程编号
                if (empty($params['schedule_no'])) {
                    $params['schedule_no'] = 'SCH' . date('Ymd') . sprintf('%04d', rand(1, 9999));
                }
                
                // 设置创建人信息
                $params['creator_id'] = $this->auth->id;
                $params['creator_name'] = $this->auth->username;
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 验证必填字段
                if (empty($params['schedule_name'])) {
                    $this->error('排程名称不能为空');
                }
                if (empty($params['start_date'])) {
                    $params['start_date'] = date('Y-m-d');
                }
                if (empty($params['end_date'])) {
                    $params['end_date'] = date('Y-m-d', strtotime('+7 days'));
                }
                
                // 验证日期格式
                if (!strtotime($params['start_date'])) {
                    $this->error('开始日期格式不正确');
                }
                if (!strtotime($params['end_date'])) {
                    $this->error('结束日期格式不正确');
                }
                
                // 验证日期逻辑
                if (strtotime($params['start_date']) > strtotime($params['end_date'])) {
                    $this->error('开始日期不能晚于结束日期');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($pk, 'in', $ids)->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 甘特图
     */
    public function gantt($ids = null)
    {
        $schedule = $this->model->get($ids);
        if (!$schedule) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $tasks = Db::name('scanwork_schedule_task')
                ->where('schedule_id', $ids)
                ->select();
            
            $ganttData = [];
            foreach ($tasks as $task) {
                $ganttData[] = [
                    'id' => $task['id'],
                    'text' => $task['task_no'],
                    'start_date' => date('Y-m-d H:i', $task['plan_start_time']),
                    'end_date' => date('Y-m-d H:i', $task['plan_end_time']),
                    'progress' => $task['completion_rate'] / 100,
                    'type' => 'task'
                ];
            }
            
            return json(['code' => 1, 'data' => $ganttData]);
        }

        $this->view->assign('schedule', $schedule);
        return $this->view->fetch();
    }

    /**
     * 产能负荷
     */
    public function capacityLoad()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));

        if ($this->request->isAjax()) {
            $loads = Db::name('scanwork_capacity_load')
                ->alias('l')
                ->join('scanwork_work_center w', 'l.work_center_id = w.id')
                ->where('l.load_date', 'between', [$startDate, $endDate])
                ->field('l.*, w.center_name')
                ->select();
            
            return json(['code' => 1, 'data' => $loads]);
        }

        return $this->view->fetch();
    }

    /**
     * 瓶颈分析
     */
    public function bottleneck()
    {
        if ($this->request->isAjax()) {
            $analysis = Db::name('scanwork_bottleneck_analysis')
                ->alias('b')
                ->join('scanwork_work_center w', 'b.work_center_id = w.id', 'LEFT')
                ->join('scanwork_equipment e', 'b.equipment_id = e.id', 'LEFT')
                ->field('b.*, w.center_name, e.equipment_name')
                ->order('b.impact_level', 'asc')
                ->order('b.load_rate', 'desc')
                ->select();
            
            return json(['code' => 1, 'data' => $analysis]);
        }

        return $this->view->fetch();
    }

    /**
     * 冲突检测
     */
    public function conflict()
    {
        if ($this->request->isAjax()) {
            $conflicts = Db::name('scanwork_schedule_conflict')
                ->alias('c')
                ->join('scanwork_schedule_task t1', 'c.task_id_1 = t1.id', 'LEFT')
                ->join('scanwork_schedule_task t2', 'c.task_id_2 = t2.id', 'LEFT')
                ->field('c.*, t1.task_no as task_no_1, t2.task_no as task_no_2')
                ->where('c.is_resolved', 0)
                ->order('c.severity', 'desc')
                ->select();
            
            return json(['code' => 1, 'data' => $conflicts]);
        }

        return $this->view->fetch();
    }
    
    /**
     * 执行排程计算
     */
    public function executeSchedule()
    {
        $scheduleId = $this->request->param('schedule_id');
        $algorithm = $this->request->param('algorithm', 'priority');
        
        if (!$scheduleId) {
            $this->error('排程ID不能为空');
        }
        
        try {
            $engine = new \app\admin\library\ScheduleEngine();
            $result = $engine->execute($scheduleId, $algorithm);
            
            $this->success('排程计算完成', null, [
                'total_tasks' => count($result),
                'scheduled_tasks' => count(array_filter($result, function($task) {
                    return isset($task['status']) && $task['status'] == 1;
                }))
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
}

